package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;
    /**
     * 处理超时支付订单
     * 每分钟检测一次
     */
    @Scheduled(cron = "0 1 * * * ?")
    public void processTimeOutOrders(){
        log.info("开始处理超时未支付的订单：{}", new Date());
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime orderTime = now.minusMinutes(15);
        //获取超过15分钟未支付的订单，并取消订单
        List<Orders> ordersList = orderMapper.getByOrderTimeAndStatus(orderTime, Orders.PENDING_PAYMENT);
        if (ordersList != null && !ordersList.isEmpty()) {
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时未支付");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            });
        }
    }

    /**
     * 处理一直派送中的订单和一直未接单、待派送的订单
     * 每天凌晨1点执行一次
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrders(){
        log.info("开始处理派送中的订单：{}", new Date());
        LocalDateTime time = LocalDateTime.now().minusMinutes(60);
        // 获取前一天凌晨12点之前还在派送的订单，并自动完成订单
        List<Orders> ordersList = orderMapper.getByOrderTimeAndStatus(time, Orders.DELIVERY_IN_PROGRESS);
        ordersList.forEach(orders -> {
            orders.setStatus(Orders.COMPLETED);
            orders.setDeliveryTime(LocalDateTime.now());
            orderMapper.update(orders);
        });
        // 获取前一天凌晨12点之前还未接单、待派送的订单，并自动取消订单
        ordersList = orderMapper.getByOrderTimeAndStatus(time, Orders.TO_BE_CONFIRMED);
        ordersList.forEach(orders -> {
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelReason("商家超时接单，自动取消");
            orders.setCancelTime(LocalDateTime.now());
            orderMapper.update(orders);
        });
    }
}
